package com.cq.controller;

import com.aliyuncs.exceptions.ClientException;
import com.cq.pojo.Admin;
import com.cq.pojo.Result;
import com.cq.pojo.Role;
import com.cq.service.AdminService;
import com.cq.service.RoleService;
import com.cq.utils.SMSUtils;
import com.cq.utils.VerifyUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 悠久的苍穹
 * @Date: 2021/1/5 17:51
 * @Description: 登录模块
 * @Version: 1.0
 */
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpSession session;

    @Autowired
    AdminService adminService;

    @Autowired
    RoleService roleService;

    @GetMapping("/getCode")
    public void getCode(HttpServletResponse response) throws Exception {
        Object[] objs = VerifyUtil.createImage();
        stringRedisTemplate.opsForValue().set(objs[0].toString(), objs[0].toString(), 3, TimeUnit.MINUTES);
        BufferedImage image = (BufferedImage) objs[1];
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "png", os);
    }

    @PostMapping("/admin/loginByPassword")
    @ResponseBody
    public Result loginByPassword(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String name = (String) map.get("name");
        String password = (String) map.get("password");
        String check = (String) map.get("check");
        String checkRedis = stringRedisTemplate.opsForValue().get(check);
        if (checkRedis == null) {
            result.setCode(500);
            result.setMsg("验证码错误或已过期");
        } else{
            if (checkRedis.equalsIgnoreCase(check)){
                Subject subject = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(name, DigestUtils.md5DigestAsHex(password.getBytes()));
                try {
                    subject.login(token);
                    Role role = roleService.findRoleByAdminId(((Admin) subject.getPrincipal()).getId());
                    subject.getSession().setAttribute("admin", subject.getPrincipal());
                    subject.getSession().setAttribute("role", role);
                    result.setCode(200);
                    result.setMsg("登陆成功");
                } catch (UnknownAccountException e) {
                    result.setCode(500);
                    result.setMsg("用户不存在");
                } catch (IncorrectCredentialsException e) {
                    result.setCode(500);
                    result.setMsg("密码错误");
                }catch (Exception e) {
                    result.setCode(500);
                    result.setMsg("用户不存在");
                }
                } else{
                result.setCode(500);
                result.setMsg("验证码错误");
            }
        }
        return result;
    }
}
